from mysqlPy import MySQLDatabase
from datetime import datetime
import requests
import json
import time
def getUserAllMedal(target_id: str):
    cookies = {
        'buvid3': '16E680AC-D635-167E-E5AB-55E09BB2422B80627infoc',
        'b_nut': '1742005280',
        '_uuid': '6AF62310A-2B3B-BB6D-4D47-7D75738DE59D75796infoc',
        'buvid_fp': 'b7767c467374bbe6d59aa1fc04af00d6',
        'buvid4': 'AE49E796-0799-55A6-2042-DD50EBB403BB81834-025031502-3JIWqK%2FcPaIok7AzeYtYhA%3D%3D',
        'header_theme_version': 'CLOSE',
        'enable_web_push': 'DISABLE',
        'enable_feed_channel': 'ENABLE',
        'home_feed_column': '4',
        'browser_resolution': '1272-602',
        'SESSDATA': '6f0d272a%2C1757557304%2Ce8c07%2A32CjCoZeZhGQkTYkv9IENDCX01oIv_q1Q9adFngN0Cm9D23CjoKJS0qWaYwuEA1SJ5dK0SVldZbEN3MGZKQkYzckRjSFphM3hUa0I1al9jaFJiWWI2dXN2c1g5UGRVQnNxRWU3X1ZjS0wwZzJWdk96N2l4U192WnZhTHRIdXBzWWV4UUIzZEtiMDZ3IIEC',
        'bili_jct': '6834aaf98c10ef7bcb62cd82b5d877e8',
        'DedeUserID': '3546869426817357',
        'DedeUserID__ckMd5': '473aaa760a206035',
        'sid': '6mtipbmx',
        'bili_ticket': 'eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDIyNjU3MDYsImlhdCI6MTc0MjAwNjQ0NiwicGx0IjotMX0.QQRwPU6rlOZj7M9-TUGSGqyVaW5fezmP26bCZCxhxfc',
        'bili_ticket_expires': '1742265646',
        'CURRENT_FNVAL': '16',
        'bp_t_offset_3546869426817357': '1044435776080707584',
        'PVID': '2',
        'b_lsid': '83110ACF3_195984172FE',
    }

    headers = {
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'no-cache',
        'origin': 'https://live.bilibili.com',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://live.bilibili.com/',
        'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Microsoft Edge";v="134"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-site',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0',
        # 'cookie': 'buvid3=16E680AC-D635-167E-E5AB-55E09BB2422B80627infoc; b_nut=1742005280; _uuid=6AF62310A-2B3B-BB6D-4D47-7D75738DE59D75796infoc; buvid_fp=b7767c467374bbe6d59aa1fc04af00d6; buvid4=AE49E796-0799-55A6-2042-DD50EBB403BB81834-025031502-3JIWqK%2FcPaIok7AzeYtYhA%3D%3D; header_theme_version=CLOSE; enable_web_push=DISABLE; enable_feed_channel=ENABLE; home_feed_column=4; browser_resolution=1272-602; SESSDATA=6f0d272a%2C1757557304%2Ce8c07%2A32CjCoZeZhGQkTYkv9IENDCX01oIv_q1Q9adFngN0Cm9D23CjoKJS0qWaYwuEA1SJ5dK0SVldZbEN3MGZKQkYzckRjSFphM3hUa0I1al9jaFJiWWI2dXN2c1g5UGRVQnNxRWU3X1ZjS0wwZzJWdk96N2l4U192WnZhTHRIdXBzWWV4UUIzZEtiMDZ3IIEC; bili_jct=6834aaf98c10ef7bcb62cd82b5d877e8; DedeUserID=3546869426817357; DedeUserID__ckMd5=473aaa760a206035; sid=6mtipbmx; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDIyNjU3MDYsImlhdCI6MTc0MjAwNjQ0NiwicGx0IjotMX0.QQRwPU6rlOZj7M9-TUGSGqyVaW5fezmP26bCZCxhxfc; bili_ticket_expires=1742265646; CURRENT_FNVAL=16; bp_t_offset_3546869426817357=1044435776080707584; PVID=2; b_lsid=83110ACF3_195984172FE',
    }

    params = {
        'target_id': target_id,
    }

    response = requests.get(
        'https://api.live.bilibili.com/xlive/web-ucenter/user/MedalWall',
        params=params,
        cookies=cookies,
        headers=headers,
    )
    return response

if __name__ == "__main__":
    # 配置数据库信息
    db_config = {
        "host": "localhost",
        "user": "root",
        "password": "111111",
        "database": "gardevoir",
        "port": 3306
    }

    target_belong = [
        "1217754423",
        "1900141897",
        "1878154667",
        "1660392980"
    ]

    with MySQLDatabase(**db_config) as db:
        sql = """
            SELECT * 
            FROM guard_user 
            WHERE guard_belong IN ({})
        """.format(','.join(['%s'] * len(target_belong)))

        results = db.execute_query(sql, tuple(target_belong))

        insert_sql = """
            INSERT INTO user_medal 
                (`create_time`, `m_id`, `close_space_medal`, `only_show_wearing`, `user_level`,
                 `medal_name`, `medal_guard`, `is_light`, `medal_level`, `medal_ruid`) 
            VALUES 
                (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        """
        insert_data = []
        for user in results:
            m_id = user["uid"]
            response = getUserAllMedal(m_id)
            current_time = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
            responseData = json.loads(response.text)['data']
            if(responseData['close_space_medal'] == 1 or responseData['only_show_wearing'] == 1):
                insert_data.append(
                    (current_time, m_id, responseData['close_space_medal'],
                     responseData['only_show_wearing'], responseData['level'],
                     '', -1,
                     -1, -1,
                     '')
                )
                continue
            for medalSingle in responseData['list']:
                insert_data.append(
                    (current_time, m_id, responseData['close_space_medal'],
                     responseData['only_show_wearing'], responseData['level'],
                     medalSingle['medal_info']['medal_name'],medalSingle['medal_info']['guard_level'],
                     medalSingle['uinfo_medal']['is_light'], medalSingle['uinfo_medal']['level'],
                     medalSingle['uinfo_medal']['ruid'])
                )
            time.sleep(0.2)
        inserted = db.execute_many(insert_sql, insert_data)
        db.commit()
        print(f"成功插入 {inserted} 条记录")
    pass